package cn.javase.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerApplication {
    private static final Logger logger = LoggerFactory.getLogger(HttpServerApplication.class);
    private static int port = 8080;

    public static void run() {
        loadBanner();
        loadProperties();
        buildTCPServer();
    }

    // 加载图标
    private static void loadBanner() {
        logger.info("\n _   _ _   _        ____                           \n" +
                "| | | | |_| |_ _ __/ ___|  ___ _ ____   _____ _ __ \n" +
                "| |_| | __| __| '_ \\___ \\ / _ \\ '__\\ \\ / / _ \\ '__|\n" +
                "|  _  | |_| |_| |_) |__) |  __/ |   \\ V /  __/ |   \n" +
                "|_| |_|\\__|\\__| .__/____/ \\___|_|    \\_/ \\___|_|   \n" +
                "              |_|                                  \n");
    }

    // 加载自定义配置
    private static void loadProperties() {
        Properties prop = new Properties();
        // 使用类加载器获取输入流
        InputStream input = null;
        try {
            // 注意：这里不需要加"/"前缀
            input = HttpServerApplication.class.getClassLoader().getResourceAsStream("application.properties");
            if (input == null) {
                logger.error("Sorry, unable to find config.properties");
                return;
            }
            // 从输入流加载属性列表
            prop.load(input);
            // 获取属性
            port = Integer.parseInt((String) prop.get("server.port"));
            logger.info("listening on port {}", port);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

    // 构建TCP服务
    private static void buildTCPServer() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            logger.info("TCP server started");
            ExecutorService pool = Executors.newFixedThreadPool(520);
            while (true) {
                Socket socket = serverSocket.accept();
                if (socket != null && !socket.isClosed()) {
                    logger.info("received connection from client...");
                    pool.submit(new HttpHandler(socket));
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
